import { ApiaddPatient, ApigetCode, ApiputPatient } from "../../../api/index"
import { errorMessage, genderSelect, nationSelect } from "./data.js"
import { debounce } from "../../../utils/index"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageTitle: "",
    genderSelect,
    nationSelect,
    ops: {
      name: "",
      gender: "",
      birth: "",
      id_number: "",
      nation: '',
      area: [],
      area_detail: "",
      phone: "",
      code: ""
    },
    error:{
      name: "",
      gender: "",
      birth: "",
      id_number: "",
      nation: '',
      area: "",
      area_detail: "",
      phone: "",
      code: ""
    },
    endTime: "",
    countdown: 0,
    codeLoading: false, 
    btnLoading: false, //提交按钮loading
    isSubmit: false,   //提交成功
    editId: null,
    genderValue: 0,
    nationValue: 0
  },
  timer: null,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const t = new Date()
    const m = t.getMonth() + 1
    const d = t.getDate()
    const endTime = `${t.getFullYear()}-${m < 10 ? ('0' + m) : m }-${d < 10 ? ('0' + d) : d }`

    if(options.item){
      const item = JSON.parse(options.item)
      const ops = {}
      let genderValue = 0, nationValue = 0
      for (const key in this.data.ops) {
        ops[key] = item[key] ?? ""
      }
      if(ops.gender ) {
        const index = genderSelect.indexOf(ops.gender)
        genderValue = Math.max(index, 0)
      }
      if(ops.nation) {
        const index = nationSelect.indexOf(ops.nation)
        nationValue = Math.max(index, 0)
      }
      this.setData({
        pageTitle: "编辑就诊人",
        endTime,
        ops,
        editId: item.id,
        genderValue,
        nationValue
      })
    }else {
      this.setData({
        pageTitle: "添加就诊人",
        endTime,
        editId: null
      })
    }
    
  },

  onClickTop() {
    wx.showToast({
      title: '此功能暂未开放',
      icon: "none"
    })
  },

  onInput(e) {
    const type = e.currentTarget.dataset.type
    const value = e.detail.value
    this.setData({
      [`ops.${type}`] : value
    })
    if(this.data.error[type]){
      this.setData({
        [`error.${type}`]: ""
      })
    }
  },

  bindgenderSelect(e) {
    this.setData({
      ['ops.gender']: genderSelect[e.detail.value] 
    })
  },

  bindBirthChange(e) {
    this.setData({
      ['ops.birth']: e.detail.value
    })
  },

  bindNationSelect(e) {
    this.setData({
      ['ops.nation']: nationSelect[e.detail.value] 
    })
  },

  bindRegionChange(e) {
    this.setData({
      ['ops.area']: e.detail.value
    })
  },

  onGetCode: debounce(function() {
    if(/^1[3-9]\d{9}$/.test(this.data.ops.phone)){
      this.setData({
        codeLoading: true
      })
      ApigetCode({phone: this.data.ops.phone }).then(res => {
        this.setData({
          countdown: 60,
        },() => {
          this.getCountdown()
        })
      }).finally(_=>{
        this.setData({
          codeLoading: false
        })
      })
    }else {
      this.setData({
        ['error.phone'] : "请输入正确手机号"
      })
    }
  },500,true),

  getCountdown() {
    this.timer = setInterval(_=>{
      const countdown = this.data.countdown - 1
      if(countdown < 1) {
        clearInterval(this.timer)
        this.timer = null
      }
      this.setData({
        countdown
      })
    },1000)
  },


  onSubmit: debounce(function(){
    let flag = false
    for (const key in this.data.ops) {
      if(!this.data.ops[key].length){
        flag = true
        this.data.error[key] = errorMessage[key]
      }
    }

    // if(!this.data.ops.code) {
    //   flag = true
    //   this.data.error.code = "请输入验证码"
    // }

    if(this.data.ops.id_number && !/^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[Xx\d]$/.test(this.data.ops.id_number)){
      flag = true
      this.data.error.id_number = "请输入正确身份证号"
    }
    
    if(flag){
      this.setData({
        error: this.data.error
      })
      return
    }

    this.submitPost()
    
  },500,true),

  async submitPost() {
    this.setData({
      btnLoading: true
    })

    try {
      if(this.data.editId) {
        await ApiputPatient(this.data.ops,this.data.editId)
      }else {
        await ApiaddPatient(this.data.ops)
      }
      app.event.emit("visitorListRefresh")
      this.setData({
        isSubmit: true
      })
    } finally {
      this.setData({
        btnLoading: false
      })
    }
  },
  onBack(){
    wx.navigateBack()
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.timer && clearInterval(this.timer)
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  
})